using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Sys;
using net_work.IService.Sys;

namespace net_work.Controllers.Sys;

[Route("api/[controller]")]
[ApiController]
public class UserController(ILogger<UserController> logger, IUserService userService) : ControllerBase
{
    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="request">分页请求实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("list")]
    [Authorize]
    public async Task<IActionResult> ListUsers([FromBody] PagedRequest request)
    {
        logger.LogInformation("获取用户列表");
        var result = await userService.GetUsersPagedAsync(request);
        return AjaxResult.Success(result);
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpGet("get")]
    [Authorize]
    public async Task<IActionResult> GetUserById([FromQuery] long userId)
    {
        logger.LogInformation("获取用户信息");
        return await userService.SelectByIdAsync(userId) is { } user
            ? AjaxResult.Success(user)
            : AjaxResult.Error();
    }

    /// <summary>
    /// 新增用户
    /// </summary>
    /// <param name="userAddRequest">新增用户实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("add")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> AddUser([FromBody] UserAddRequest userAddRequest)
    {
        logger.LogInformation("新增用户");
        var userId = await userService.InsertUser(userAddRequest);
        return userId > 0
            ? AjaxResult.Success(new { userId })
            : AjaxResult.Error();
    }

    /// <summary>
    /// 修改用户
    /// </summary>
    /// <param name="userUpdateRequest">修改用户实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("update")]
    [Authorize]
    public async Task<IActionResult> UpdateUser([FromBody] UserUpdateRequest userUpdateRequest)
    {
        logger.LogInformation("修改用户");
        return await userService.UpdateUser(userUpdateRequest) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="ids">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("delete")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> DeleteUser([FromBody] List<long> ids)
    {
        logger.LogInformation("删除用户");
        return await userService.DeleteUserByIds(ids) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }
}